#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#include<signal.h>
#define BACKLOG 5
using namespace std;

class httpServer
{

  private:
    int port;
    int lsock;
  public:
    httpServer(int _port=8080,int _lsock= -1)
    :port(_port)
     ,lsock(_lsock)
    {}
   void initServer()
   {
     signal(SIGCHLD,SIG_IGN);
      lsock=socket(AF_INET,SOCK_STREAM,0);
      if(lsock < 0)
      {
        cerr<<"socket error"<<endl;
        exit(2);
      }
      struct sockaddr_in local;
      local.sin_family = AF_INET;
      local.sin_port = htons(port);
      local.sin_addr.s_addr = INADDR_ANY;
      if(bind(lsock,(struct sockaddr*)&local,sizeof(local)) < 0)
      {
        cerr<<"bind error"<<endl;
        exit(3);      
      }
      if(listen(lsock,BACKLOG) < 0)
      {
        cerr<<"listen error"<<endl;
        exit(4);
      }

   }
   void EchoHttp(int sock)
   {
      char response[2048];
      ssize_t s = recv(sock,response,sizeof(response),0);
      if(s > 0)
      {
          response[s] = 0;
          string response = "HTTP/1.0 200 OK\r\n";
          response += "Content-type: text/html\r\n";
             
          response += "\r\n";

          response += "<html><h1>hello </h1></html>";
        send(sock,response.c_str(),response.size(),0);

   }
      close(sock);
 }
   void start()
   {
     struct sockaddr_in peer;
     for(;;){
     socklen_t len = sizeof(peer);
      int sock = accept(lsock,(struct sockaddr*)&peer,&len);
      if(sock < 0)
      {
        cerr<<"accept error"<<endl;
        continue;
      }
     if(fork() == 0)
     {
       close(lsock);
       EchoHttp(sock);
       exit(0);
     }
     close(sock);
   }
}
    ~httpServer()
    {
      if(lsock != -1)
      {
        close(lsock);
      }
    }
};
